sociall.messages = {
	
	aForm : null,			//the form for sending messages
	checkboxes : null,	//social account checkboxes we want to highlight them whe thy are selected
	accLogos : null,	//social account logos
	messageBox : null,	//message textarea
	chc : null,				//span holds charcounts
	RTIME : 120,			//default value for the next request
	nextRequest : 7,		//next request in seconds: after pageload we do not want to wait so long
	cB : null,				//html element for displaying countBack info
	ajaxloaderMenu : null,	//ajax loader image in the menu
	ajaxloaderMess : null,	//ajax loader image at the top of messages
	ajaxloaderSend : null,	//ajax loader imageat sending
	t : null,				//timeout container
	timeline : null,		//timeline container
	mygravatarUrl : null,		//my avatar url
	timed : null,			//timed div
	timeBox : null,		//input for providing time
	
	info : {
		getTimeline	:	'Error getting timeline',
		getResponse	:	'Error getting response',
		noMessage	:	'Please type in a message to send',
		noAccount	:	'Please choose at least one account',
		timedMessage:	'This message will be sent at '
		},
	
	init : function(){
		sociall.messages.aForm = $('MessageSendForm');
		sociall.messages.checkboxes = sociall.messages.aForm.getInputs('checkbox');
		sociall.messages.accLogos = $$('.acc');
		//sociall.messages.accLogos.each(function(accLogo){
			Event.observe(document, 'click', sociall.messages.clickHandler);
			//});
		
		sociall.messages.messageBox = $('MessageMessage');
		Event.observe(sociall.messages.messageBox, 'input', sociall.messages.countChars);
		sociall.messages.chc = $('chc');
		
		Sortable.create('accs');
		
		sociall.messages.cB = $('cB');
		sociall.messages.countBack();
		
		sociall.messages.ajaxloaderMenu = $('ajaxloaderMenu');
		sociall.messages.ajaxloaderMess = $('ajaxloaderMess');
		sociall.messages.ajaxloaderSend = $('ajaxloaderSend');
		sociall.messages.timeline = $('timeline');
		
		Event.observe(document, 'submit', sociall.messages.sendMessage);
		
		sociall.messages.mygravatarUrl = $('mygravatar').src;
		
		sociall.messages.timedClock = $('timedClock');
		sociall.messages.timeBox = $('timeBox');
		sociall.messages.timeDate = $('MessageDate');
		sociall.messages.timeTime = $('MessageTime');
		new inputmask('date_iso', sociall.messages.timeDate);
		new inputmask('time_24', sociall.messages.timeTime);
		Event.observe(sociall.messages.timeTime, 'blur',function(){$('messageSubmit').focus()});
	},//sociall.message.init
	
	clickHandler : function(e){
		//handles all of the click events
		if(sociall.messages.accLogos.indexOf(e.target.parentNode.parentNode) != -1)	//account is choosen
			sociall.messages.cboxHandler(e);
		else if(e.target.className == 'mu'){	//username clicked
			sociall.messages.messageBox.value += e.target.innerHTML + ' ';
		}
		else if(e.target == sociall.messages.cB){			//countback clicked set the counter to 0
			sociall.messages.nextRequest = 0;
			sociall.messages.countBack();
		}
		else if(e.target == sociall.messages.timedClock){	//timed messages
			if(sociall.messages.timedClock.className == 'inactive_timed'){
				e.target.removeClassName('inactive_timed');
				e.target.addClassName('active_timed');
				sociall.messages.timeBox.show();
				//adding default values
				sociall.messages.timeDate.focus();
				sociall.messages.timeTime.focus();
			}
			else{
				e.target.removeClassName('active_timed');
				e.target.addClassName('inactive_timed');
				sociall.messages.timeBox.hide();
				sociall.messages.timeDate.value = sociall.messages.timeTime.value = null;
			}
		}
		/*else
			console.log(e.target.className);*/
	},//sociall.messages.clickHandler
	
	cboxHandler : function(e){
		//handle account logos
		if(e.target.nodeName == 'IMG'){
			var id = e.target.id.match(/\d+/);
			var cbox = $('AccountAccount' + id[0]);
			if(e.target.className == 'inactive_logo'){
				//account logo and checkbox activation
				cbox.checked = true;
				e.target.removeClassName('inactive_logo');
				e.target.addClassName('active_logo');
				e.target.title += ' [active]';
			}
			else{
				cbox.checked = false;
				e.target.removeClassName('active_logo');
				e.target.addClassName('inactive_logo');
				e.target.title = e.target.title.replace(/ \[active\]/, '');
			}
		}
		if(e) Event.stop(e); return false;
	},//sociall.messages.cboxHandler
	
	countChars : function(){
		//count chars in the message box
		var moreChars = parseInt(140-sociall.messages.messageBox.value.length);
		sociall.messages.chc.className = '';
		if(moreChars >= 19){
			sociall.messages.chc.addClassName('mh140');
		}
		else if(moreChars < 19 && moreChars >= 9){
			sociall.messages.chc.addClassName('mh19');
		}
		else if(moreChars < 9 && moreChars >= 0){
			sociall.messages.chc.addClassName('mh9');
		}
		else if(moreChars < 0){
			sociall.messages.chc.addClassName('mh0');
		}
		sociall.messages.chc.update(moreChars);
	},//sociall.messages.countChars
	
	saveAccOrder : function(){
		//alert(Sortable.serialize('accs'));		//save to cookie: accs[]=4&accs[]=2&accs[]=1&accs[]=3
	},//sociall.messages.saveAccOrder
	
	countBack : function(){
		//count backs for 2 minutes to get new messages
		if(sociall.messages.nextRequest > 0){
			sociall.messages.cB.update(' (' + sociall.messages.nextRequest-- + ' s)');
			sociall.messages.t = setTimeout(this.countBack.bind(this), 1000);
		}
		else{
			//ajax request
			new Ajax.Request(
				sociall.baseUrl + 'intercepts/gettimeline.json',
				{
					method: 'post',
					onCreate: function(){
						sociall.messages.cB.hide();
						sociall.messages.ajaxloaderMenu.show();
						sociall.messages.ajaxloaderMess.show();
						clearTimeout(sociall.messages.t);
					},
					onComplete : function(valasz){
						if(valasz.responseJSON){
							var entryCount = valasz.responseJSON.length;
							var entry = null;
							for(var i = 0; i < entryCount; i++){
								entry = sociall.messages.createEntry(valasz.responseJSON[i]);
								sociall.messages.timeline.insert({top : entry});
								//if(window.callout){	//if callout extension is available
								if(window.fluid){	//if yip extension is available
									var r = valasz.responseJSON[i];
									sociall.messages.callNotify({
																		name : r.community + '@' + r.username,
																		message : r.message,
																		icon : r.avatar
																		}, i+1);
								}
							}
						}
						else if(valasz){
							sociall.notify.box.update(sociall.messages.info.getTimeline);
							sociall.notify.evnt = new Effect.Notify(sociall.notify.container, {notify : {top : 5, left : 300}, fade : {delay : 12}});
						}
						sociall.messages.ajaxloaderMenu.hide();
						sociall.messages.ajaxloaderMess.hide();
						sociall.messages.cB.show();
						sociall.messages.nextRequest = sociall.messages.RTIME;
						sociall.messages.countBack();
					}
				}
			);
		}
	},//sociall.messages.countBack
	
	reformMessage : function(message){
		message = message.replace(/src="http/, 'src="ht_tp');	//mas out http in src attribs
           
      //create links from http:// strings
      message = message.gsub(/(http:\/\/\S*)/,
													function(aLink){
														return('<a href="'+aLink[0]+'" target="_blank">'+aLink[0]+'</a>')
													});
            
      message = message.replace(/src="ht_tp/, 'src="http');	//put src attribs back
		return(message);
	},//sociall.messages.reformMessage
	
	sendMessage : function(e){
		var hasChecked = false;
		sociall.messages.checkboxes.each(function(cbox){
			if(cbox.checked)
				hasChecked = true;
		});
		if(sociall.messages.messageBox.value && hasChecked){
			var url = sociall.baseUrl + (sociall.messages.timeDate.value ? 'timeds/add.json' : 'messages/send.json');
			//var url = sociall.baseUrl + 'messages/send.json';
			new Ajax.Request(
				url,
				{
					method: 'post',
					parameters : sociall.messages.aForm.serialize(),
					onCreate: function(){
						sociall.messages.ajaxloaderSend.show();
						sociall.messages.ajaxloaderMess.show();
					},
					onComplete : function(valasz){
						if(valasz.responseJSON){
							var r = valasz.responseJSON;							
							var theMessage = {
											message		:	sociall.messages.messageBox.value,
											url			:	null,
											avatar		:	sociall.messages.mygravatarUrl,
											created		:	r.created,
											details		:	new Array(),
											timed			:	r.timed
											};
							var rl = r.details.length;
							for(i = 0; i < rl; i++){
								var ri = r.details[i];
								theMessage.details[i] = {
									community	:	ri.community,
									extra			:	ri.extra,
									targetuser	:	ri.username,
									username		:	ri.username
									};
							}
							sociall.messages.messageBox.value = null;
							sociall.messages.countChars();
							var entry = sociall.messages.createEntry(theMessage);
							sociall.messages.timeline.insert({top : entry});
						}
						else if(valasz){
							sociall.notify.box.update(sociall.messages.info.getResponse);
							sociall.notify.evnt = new Effect.Notify(sociall.notify.container, {notify : {top : 5, left : 300}, fade : {delay : 12}});
							if(window.console)
								console.log(valasz.responseText);	//todo: remove
						}
						sociall.messages.messageBox.focus();
						sociall.messages.ajaxloaderSend.hide();
						sociall.messages.ajaxloaderMess.hide();
					}
				});
		}
		else{
			if(!hasChecked)
				sociall.notify.box.update(sociall.messages.info.noAccount);
			else
				sociall.notify.box.update(sociall.messages.info.noMessage);
			sociall.notify.evnt = new Effect.Notify(sociall.notify.container, {notify : {top : 5, left : 300}, fade : {delay : 12}});
		}
		if(e) Event.stop(e); return false;
	},//sociall.messages.sendMessage
	
	createEntry : function(responseJSON){
		//creates html element for a messages entry which could be attached to the dom
		var message = sociall.messages.reformMessage(responseJSON['message']);
		var _message = message;
		message = new Element('p').update(message);
		
		if(responseJSON.details){		//this is a sent message
			var logos = new Element('span');
			var rl = responseJSON.details.length;
			var username = '';
			if(responseJSON.timed){
				//this is a timed message
				logos.insert({top : Builder.node('img',
									{
										className	:	'inactive_timed',	//azért inaktív mert a közösségi ikonok 3 emeletesek ez meg csak kettő
										title			:	sociall.messages.info.timedMessage + responseJSON.timed,
										alt			:	sociall.messages.info.timedMessage + responseJSON.timed,
										src			:	sociall.baseUrl + 'img/clock.png'
									})
							 });
				
			}
			for(i = 0; i < rl; i++){
				var rd = responseJSON.details[i];
				logos.insert({bottom : Builder.node('img',
									{
										className	:	(rd['extra'] == 'error') ? 'error_logo' : 'active_logo',
										title			:	rd['community'] + '/' + rd['targetuser'],
										alt			:	rd['community'] + '/' + rd['targetuser'],
										src			:	sociall.baseUrl + 'img/logo_' + rd['community'] + '.png'
									})
							 });
				username += ' @' + rd['username'];
			}
		}
		else{		//this is an intercepted message
			var logos = Builder.node('span',
													Builder.node('img',
														{
															className	:	(responseJSON['extra'] == 'error') ? 'error_logo' : 'active_logo',
															title			:	responseJSON['community'] + '/' + responseJSON['targetuser'],
															alt			:	responseJSON['community'] + '/' + responseJSON['targetuser'],
															src			:	sociall.baseUrl + '/img/logo_' + responseJSON['community'] + '.png'
														}
													)
												);
			var username = '@' + responseJSON['username'];
		}
		
		var entry =
					Builder.node('div',
										{
											className : 'entry'
										},
										[
											Builder.node('div',
												{
													className : 'logos'
												},
												logos
											),
											Builder.node('div',
												{
													className : (responseJSON['extra'] == 'd') ? 'm d' : 'm'
												},
												[
													(responseJSON['url']) ? Builder.node('a',
																										{
																											href : responseJSON['url']
																										},
																										 Builder.node('img',
																																{
																																	className	:	'mygravatar',
																																	src			:	responseJSON['avatar']
																																}
																														)
																								)
																				: Builder.node('img',
																										{
																											className	:	'mygravatar',
																											src			:	responseJSON['avatar']
																										}
																									),
													message,
													Builder.node('p',
														{
															className	:	'mtime'
														},
														[
															Builder.node('span',
																{
																	className	:	'mu'
																},
																username
															),
															responseJSON['created']
														]
													)
												]
											)
										]
								);
		return(entry);
	},//sociall.messages.createEntry
		
	callNotify : function(data, i){
		//we need this extra code to handle settieout & this correctly
		//if we put this into the ajax.onComplete this will point to the window object - it looses connection with sociall
		setTimeout(this.offBrowserNotify.bind(this, data), i*3500);
	},//sociall.messages.callNotify
	
	offBrowserNotify : function(user){
		//deprecated
			//if callout FF extension (https://addons.mozilla.org/en-US/firefox/addon/7458/) is available notify the user
			/*callout.notify(
								user.name,
								user.message,
								{
									icon: user.icon
								}
							);*/
		//if yip extension is available http://www.yipyip.com/
		fluid.showGrowlNotification(
											{
											title : user.name,
											description : user.message,
											icon: user.icon
											});
	}//sociall.messages.offBrowserNotify
}

document.observe('dom:loaded', function(){
	sociall.messages.init();
	});
Event.observe(window, 'unload', sociall.messages.saveAccOrder);